#include "CEUtilities.h"

#include "CELight.h"
#include "CEGraphicLayer.h"


//----------------------------------------------------------------------
Light::Light(const STRING &name,
			 Object *father,
			 const Vector3 &offset,
			 const Radian &radianX, const Radian &radianY, const Radian &radianZ,
			 BOOL isVisible)
	: MovableObject(name, 
					father, 
					offset, 
					radianX,
					radianY,
					radianZ,
					isVisible)
{
	InitLight(TRUE, D3DLIGHT_DIRECTIONAL);
	m_dwIndex = _GetIndex();
}


//----------------------------------------------------------------------
Light::~Light()
{
}


//----------------------------------------------------------------------
void Light::InitLight(BOOL enable,
					  D3DLIGHTTYPE Type,
					  Color &diffuse, Color &specular, Color &ambient,
					  REAL range,
					  REAL falloff,
					  REAL attenuation0, REAL attenuation1, REAL attenuation2,
					  REAL theta,
					  REAL phi)
{
	m_Light.Type			= Type;
	m_Light.Diffuse			= diffuse.GetAsD3DCOLOR();
	m_Light.Specular		= specular.GetAsD3DCOLOR();
	m_Light.Ambient			= ambient.GetAsD3DCOLOR();
	m_Light.Range			= range;
	m_Light.Falloff			= falloff;
	m_Light.Attenuation0	= attenuation0;
	m_Light.Attenuation1	= attenuation1;
	m_Light.Attenuation2	= attenuation2;
	m_Light.Theta			= theta;
	m_Light.Phi				= phi;

	m_Light.Position.x		= GetPosition().x;
	m_Light.Position.y		= GetPosition().y;
	m_Light.Position.z		= GetPosition().z;
	m_Light.Direction.x		= GetDir().x;
	m_Light.Direction.y		= GetDir().y;
	m_Light.Direction.z		= GetDir().z;

	m_bEnable				= enable;
}


//----------------------------------------------------------------------
DWORD Light::_GetIndex()
{
	static DWORD index = 0;
	return index++;
}


//----------------------------------------------------------------------
D3DLIGHT9* Light::GetLight()
{
	return &m_Light;
}


//----------------------------------------------------------------------
HRESULT Light::LightEnable(BOOL bEnable)
{
	m_bEnable = bEnable;
	
	return GraphicLayer::GetSingleton()->LightEnable(m_dwIndex, m_bEnable);
}


//----------------------------------------------------------------------
HRESULT Light::FrameMove(REAL deltTime)
{
	HRESULT r = MovableObject::FrameMove(deltTime);

	m_Light.Position.x  = GetPosition().x;
	m_Light.Position.y  = GetPosition().y;
	m_Light.Position.z  = GetPosition().z;
	m_Light.Direction.x = GetDir().x;
	m_Light.Direction.y = GetDir().y;
	m_Light.Direction.z = GetDir().z;

	return r;
}


//----------------------------------------------------------------------
HRESULT Light::RestoreDeviceObjects()
{
	GraphicLayer::GetSingleton()->SetLight(m_dwIndex, this);
	GraphicLayer::GetSingleton()->LightEnable(m_dwIndex, m_bEnable);

	return MovableObject::RestoreDeviceObjects();
}